﻿using System;
using System.Data;

namespace TXTMonitor
{
    internal class SaveDBProcess:ProcessFileBase,IDisposable
    {
        #region Private Members
        private DDNP.Supports.Common.DDNPSqlDatabase targetExchangDB;
        private string dataType;
        private string monitorPath;
        private string targetTable;
        private string _dataFilter;
        private string _splitChar;
        private string _splitArr;
        private bool isInitialize = false;
        #endregion


        #region Public Properties
        public string DataFilter
        {
            get 
            {
                return this._dataFilter;
            }
            set
            {
                this._dataFilter = value;
            }
        }
        public string SplitChar
        {
            get 
            {
                return this._splitChar;
            }
            set
            {
                this._splitChar = value;
            }
        }
        #endregion

        

        #region Constructor
        public SaveDBProcess()
        {
            //this.targetExchangDB = TargetExchangDB;
            //this.dataType = DataType;
            //this.monitorPath = MonitorPath;
            //this.targetTable = TargetTable;
            //this._splitChar = "^";
            base._processType = ProcessType.ExChangeDB;
        }
        #endregion
        #region IProcessFile Members
        public override void Initialize(ProcessType processType, System.Collections.Specialized.NameValueCollection config)
        {
          
            #region Set Data 
            if (!string.IsNullOrEmpty(config["DBConnString"]))
            {
                this.targetExchangDB = new DDNP.Supports.Common.DDNPSqlDatabase(config["DBConnString"]);
            }
            else
            {
                throw new Exception("Must set DBConnString");
            }
            if (!string.IsNullOrEmpty(config["MonitorPath"]))
            {
                this.monitorPath = config["MonitorPath"];
            }
            else
            {
                throw new Exception("Must set MonitorPath");
            }
            if (!string.IsNullOrEmpty(config["TargetTable"]))
            {
                this.targetTable = config["TargetTable"];
            }
            else
            {
                throw new Exception("Must set TargetTable");
            }
            if (!string.IsNullOrEmpty(config["DataType"]))
            {
                this.dataType = config["DataType"];
            }
            else
            {
                throw new Exception("Must set DataType");
            }
            if (!string.IsNullOrEmpty(config["SplitChar"]))
            {
                this._splitChar = config["SplitChar"];
            }
            else
            {
                this._splitChar = "^";
            }
            this._splitArr = config["SplitArr"];
            if (!string.IsNullOrEmpty(config["DataFilter"]))
            {
                this._dataFilter = config["DataFilter"];
            }
            else
            {
                this._dataFilter = "";
            }
            #endregion
            this.isInitialize = true;
            base.Initialize(processType, config);
            
        }

        public override void ProcessFile(string PlantCode, string filename, string filePath)
        {
            if (this.isInitialize)
            {
                DataTable _dtScheml = FileUtility.DBUtility.GetDataTableNoData(targetExchangDB, targetTable);
                string _Prifix, _fileCountsExt;
                int totalFiles, currentFile;
                if (filename.IndexOf("(") > 0)
                {
                    _Prifix = filename.Substring(0, filename.LastIndexOf("("));
                    _fileCountsExt = filename.Substring(filename.LastIndexOf("(") + 1, filename.LastIndexOf(")") - filename.LastIndexOf("(") - 1);
                    totalFiles = Int32.Parse(_fileCountsExt.Substring(0, _fileCountsExt.IndexOf("_")));
                    currentFile = Int32.Parse((_fileCountsExt.Substring(_fileCountsExt.IndexOf("_"), _fileCountsExt.Length - _fileCountsExt.IndexOf("_"))).TrimStart("_".ToCharArray()));
                }
                else
                {
                    _Prifix = filename.Substring(0, filename.LastIndexOf("."));
                    totalFiles = 1;
                    currentFile = 1;
                }
                bool IsNew = true;

                Guid batchId = FileUtility.DBUtility.GetBatchID("Forecast", targetExchangDB, "TransferLogT", _Prifix, out IsNew);
                if (IsNew)
                {
                    currentFile = 0;
                    FileUtility.DBUtility.AddNewFileLog(targetExchangDB, batchId, dataType, monitorPath, _Prifix, totalFiles, currentFile, 0, -1, PlantCode);
                }
                try
                {

                    
                    //if (string.IsNullOrEmpty(this._dataFilter))
                    //{

                    //}
                    DataTable dtContent;
                    if (string.IsNullOrEmpty(this._splitArr))
                    {
                        dtContent = FileUtility.FileUtility.ReadFileContentToDataTable(filePath, _dtScheml, batchId, this._splitChar);
                    }
                    else
                    {
                        string[] inputArr = this._splitArr.Split(",".ToCharArray());
                        int[] splitLenthArr = Array.ConvertAll<string, int>(inputArr, s => { return Int32.Parse(s); });
                        dtContent = FileUtility.FileUtility.ReadFileContentToDataTable(filePath, _dtScheml, batchId, splitLenthArr);
                    }
                    string _connString = targetExchangDB.CreateConnection().ConnectionString;
                    System.Data.SqlClient.SqlBulkCopy sqlBulkCopy = new System.Data.SqlClient.SqlBulkCopy(_connString, System.Data.SqlClient.SqlBulkCopyOptions.UseInternalTransaction);
                    sqlBulkCopy.DestinationTableName = targetTable;
                     
                    sqlBulkCopy.BulkCopyTimeout = 360;
                    DataTable dtSchema = this.GetSchema(targetTable, _connString);
                    //  CheckData(dtContent, dtSchema);
                    if (!string.IsNullOrEmpty(_dataFilter))
                    {
                        sqlBulkCopy.WriteToServer(dtContent.Select(_dataFilter));
                        FileUtility.DBUtility.AddFileCount(targetExchangDB, batchId, dtContent.Select(this._dataFilter).Length);
                    }
                    else
                    {
                        sqlBulkCopy.WriteToServer(dtContent);
                        FileUtility.DBUtility.AddFileCount(targetExchangDB, batchId, dtContent.Rows.Count);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message);
                   // FileUtility.Utility.SaveException(targetExchangDB, batchId, ex.Message, filename);
                }
            }
            else
            {
                throw new Exception("Must Initialize");
            }
        }
        #endregion

        #region IDisposeable Member
        public void Dispose()
        {
            this.isInitialize = false;
            this.targetExchangDB = null;
        }
        #endregion

        #region Private Method
        private DataTable GetSchema(string dtName, string connStr)
        {
            System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr);
            conn.Open();
            string cmdtext = string.Format("select c.name,c.length from syscolumns c,systypes t,sysobjects o where t.xusertype=c.xtype and o.id=c.id and o.name='{0}' order by c.colid", dtName);
            DataTable dtSchema = new DataTable();
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(cmdtext, conn);
            System.Data.SqlClient.SqlDataAdapter dap = new System.Data.SqlClient.SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            dap.Fill(ds);
            dtSchema = ds.Tables[0];
            conn.Close();
            return dtSchema;
        }
        #endregion
    }

}
